const { createUser, createService, serviceLogin, getServiceList, deleteService, updateService, getUserList } = require('../model/user');
const { getFriendList, getChatList } = require('../model/chatList');
const { redisSet, redisGet } = require('../utils/redis');
const { v4: uuidv4 } = require('uuid');
const { getUserInfo } = require('../model/user');
const { sendNotification } = require('../mq/chatMsg');
const { createToken } = require('../utils/token');
const md5 = require('md5');
const { md5Secret } = require('../config');
const path = require('path');
const fs = require('fs');
const { createFriend } = require('../model/chatList');

const createUserController = async (req, res) => {
    let { userId, userName, avatar, userType } = req.body;
    if (!userId) {
        return res.json({
            code: 500,
            message: 'userId 不能为空'
        });
    }
    if (!userName) {
        return res.json({
            code: 500,
            message: 'userName 不能为空'
        });
    }
    // if (!avatar) {
    //     return res.json({
    //         code: 500,
    //         message: 'avatar 不能为空'
    //     });
    // }
    if (!avatar) avatar = ''
    if (!userType) {
        return res.json({
            code: 500,
            message: 'userType 不能为空'
        });
    }
    try {
        // DB- 创建用户
        const result = await createUser({ userId, userName, avatar, userType });
        // Redis- 创建用户
        if (result.result && result.result._id) {
            await redisSet(`mim-${result.result._id}`, {
                userId,
                userName,
                avatar,
                userType: Number(userType),
                imKey: result.result._id.toString()
            })
            // 给用户初始化一个客服好友
            const findService = await getServiceList({ userName: '技能猴子官方' });
            if (findService && findService.length > 0) {
                await createFriend({
                    user: result.result._id.toString(),
                    toUser: findService[0]._id.toString(),
                    lastMessage: '',
                    isEnd: true,
                    createTime: Date.now(),
                    updateTime: Date.now()
                })
            }
        }
        res.json({
            code: 200,
            message: result.type === 'create' ? 'IM用户创建成功' : 'IM用户信息已更新',
            data: {
                dataType: result.type,
                imKey: result.result._id.toString()
            }
        });
    } catch (error) {
        res.json({
            code: 500,
            message: '创建失败',
            data: error.message
        });
    }
}

// 服务端推送通知消息
const sysPushMsg = async (req, res) => {
    try {
        let { userId, content, contentType, exData } = req.body;
        if (!userId) {
            return res.json({
                code: 500,
                message: 'userId 不能为空'
            });
        }
        if (!content) {
            return res.json({
                code: 500,
                message: 'content 不能为空'
            });
        }
        if (!contentType) {
            return res.json({
                code: 500,
                message: 'contentType 不能为空'
            });
        }
        if (exData) {
            try {
                exData = JSON.parse(exData);
            } catch (e) {
                exData = {};
            }
        }
        // 推送消息
        const userInfo = await getUserInfo(userId);
        if (userInfo && userInfo._id) {
            const toUserInfo = await redisGet(`mim-${userInfo._id.toString()}`);
            if (toUserInfo) {
                const fromUserInfo = await redisGet(`mim-OrderAssistant`);
                const msgData = {
                    from: fromUserInfo.imKey,
                    fromName: fromUserInfo.userName,
                    fromAvatar: fromUserInfo.avatar,
                    fromType: fromUserInfo.userType,
                    to: toUserInfo.imKey,
                    toName: toUserInfo.userName,
                    toAvatar: toUserInfo.avatar,
                    toType: toUserInfo.userType,
                    content: content,
                    contentType: Number(contentType),
                    exData: exData,
                    msgKey: uuidv4(),
                    time: new Date().getTime(),
                }
                await sendNotification(msgData);
                return res.json({
                    code: 200,
                    message: '推送成功'
                });
            } else {
                return res.json({
                    code: 500,
                    message: 'IM系统内未找到该用户'
                });
            }
        } else {
            return res.json({
                code: 500,
                message: '用户不存在'
            });
        }
    } catch (e) {
        res.json({
            code: 500,
            message: '推送失败',
            data: e.message
        });
    }
}

// 初始化创建系统用户
const initSystemUser = async () => {
    try {
        // 初始化订单助手
        const result = await createUser({ userId: 'OrderAssistant', userName: '订单助手', avatar: '', userType: 4 });
        if (result && result.result && result.result._id) {
            await redisSet(`mim-OrderAssistant`, {
                userId: 'OrderAssistant',
                userName: '订单助手',
                avatar: '',
                userType: 4,
                imKey: result.result._id.toString()
            })
            await redisSet(`mim-${result.result._id.toString()}`, {
                userId: 'OrderAssistant',
                userName: '订单助手',
                avatar: '',
                userType: 4,
                imKey: result.result._id.toString()
            })
        }

        try {
            // 初始化IM客服用户
            const addRes = await createService({
                userId: 'IMservice',
                userName: '技能猴子官方',
                avatar: '',
                userType: 3
            });
            console.log('addRes', addRes)
            if (addRes && addRes._id) {
                await redisSet(`mim-IMservice`, {
                    userId: 'IMservice',
                    userName: '技能猴子官方',
                    avatar: '',
                    userType: 3,
                    imKey: addRes._id.toString()
                })
                await redisSet(`mim-${addRes._id.toString()}`, {
                    userId: 'IMservice',
                    userName: '技能猴子官方',
                    avatar: '',
                    userType: 3,
                    imKey: addRes._id.toString()
                })
            }
        } catch (e) {
            console.log(e);
        }

        try {
            // 初始化一个超级管理员
            await createService({ userName: 'admin', password: md5('123456' + md5Secret), userType: 6 });
        } catch (err) {
            console.log(err);
        }
        return Promise.resolve(result);
    } catch (e) {
        console.log(e);
        return Promise.reject(e);
    }
}

// 创建客服
const createServiceController = async (req, res) => {
    try {
        let { userName, password, avatar } = req.body;
        if (!userName) {
            return res.json({
                code: 500,
                message: 'userName 不能为空'
            });
        }
        if (!password) {
            return res.json({
                code: 500,
                message: 'password 不能为空'
            });
        }
        if (!avatar) {
            return res.json({
                code: 500,
                message: 'avatar 不能为空'
            });
        }
        // MD5加密
        password = md5(password + md5Secret);
        const addData = {
            userName,
            password,
            avatar,
            userType: 3
        }
        const result = await createService(addData);
        res.json({
            code: 200,
            message: '创建成功',
            data: result
        });
    } catch (e) {
        res.json({
            code: 500,
            message: e.message
        });
    }
}

// 客服登录
const serviceLoginController = async (req, res) => {
    try {
        let { userName, password } = req.body;
        if (!userName) {
            return res.json({
                code: 500,
                message: 'userName 不能为空'
            });
        }
        if (!password) {
            return res.json({
                code: 500,
                message: 'password 不能为空'
            });
        }
        // MD5加密
        password = md5(password + md5Secret);
        const addData = {
            userName,
            password,
            userType: userName === 'admin' ? 6 : 3
        }
        const result = await serviceLogin(addData);
        if (result) {
            // 将 Mongoose 文档转换为普通对象
            const userInfo = result.toObject ? result.toObject() : result;
            const token = await createToken(userInfo)
            // Redis- 创建用户
            await redisSet(`mim-${result._id}`, {
                userId: result._id,
                userName: result.userName,
                avatar: result.avatar,
                userType: Number(result.userType),
                imKey: result._id.toString(),
                socketId: null,
                online: 0
            })
            res.json({
                code: 200,
                message: '登录成功',
                data: {
                    token,
                    userInfo,
                    imKey: result._id.toString()
                },

            });
        } else {
            res.json({
                code: 500,
                message: '账号或密码错误'
            });
        }
    } catch (e) {
        console.log(e);
        res.json({
            code: 500,
            message: '登录失败',
            data: e.message
        });
    }
}

// 客服列表
const serviceListController = async (req, res) => {
    try {
        const params = req.query;
        if (params.online) params.online = params.online === 'true' ? true : false;
        if (params.onDuty) params.onDuty = params.onDuty === 'true' ? true : false;
        const result = await getServiceList(params);
        res.json({
            code: 200,
            message: '获取成功',
            data: result
        });
    } catch (err) {
        res.json({
            code: 500,
            message: err.message
        });
    }
}

// 上传头像,保存到public/avatar
const uploadAvatarController = async (req, res) => {
    try {
        if (!req.files || !req.files.file) {
            return res.json({
                code: 500,
                message: '请选择要上传的文件'
            });
        }

        const file = req.files.file;

        // 检查文件类型
        if (!file.mimetype.startsWith('image/')) {
            return res.json({
                code: 500,
                message: '只能上传图片文件'
            });
        }

        // 创建文件名
        const fileName = Date.now() + '-' + file.name;
        const filePath = path.join(__dirname, '../public/avatar', fileName);

        // 确保 avatar 目录存在
        const avatarDir = path.join(__dirname, '../public/avatar');
        if (!fs.existsSync(avatarDir)) {
            fs.mkdirSync(avatarDir, { recursive: true });
        }

        // 移动文件
        await file.mv(filePath);

        res.json({
            code: 200,
            message: '上传成功',
            data: `/avatar/${fileName}` // 返回相对路径
        });
    } catch (error) {
        console.error('文件上传错误:', error);
        res.json({
            code: 500,
            message: '文件上传失败',
            data: error.message
        });
    }
}

// 删除客服
const deleteServiceController = async (req, res) => {
    try {
        console.log(req)
        const { id } = req.body;
        const result = await deleteService(id);
        res.json({
            code: 200,
            message: '删除成功',
            data: result
        });
    } catch (e) {
        res.json({
            code: 500,
            message: e.message
        });
    }
}

// 更新客服
const updateServiceController = async (req, res) => {
    try {
        const { _id, ...data } = req.body;
        if (data.password) {
            data.password = md5(data.password + md5Secret);
        }
        const result = await updateService(_id, data);
        res.json({
            code: 200,
            message: '更新成功',
            data: result
        });
    } catch (e) {
        res.json({
            code: 500,
            message: e.message
        });
    }
}

// 获取所有买家卖家列表
const getUserListController = async (req, res) => {
    try {
        const params = req.query;
        if (params.online) params.online = params.online === 'true' ? true : false;
        const result = await getUserList(params || {});
        res.json({
            code: 200,
            message: '获取成功',
            data: result
        });
    } catch (e) {
        res.json({
            code: 500,
            message: e.message
        });
    }
}

// IM管理端用-沟通列表
const getChatListController = async (req, res) => {
    try {
        const params = req.query;
        if (!params.user) {
            return res.json({
                code: 500,
                message: 'user 不能为空'
            });
        }
        const result = await getFriendList(params.user, params);
        // 遍历result，从redis中获取好友信息
        const friendList = await Promise.all(JSON.parse(JSON.stringify(result.friendList)).map(async (item) => {
            const friend = await redisGet(`mim-${item.friendId}`);
            return {
                ...item,
                friend
            }
        }));
        res.json({
            code: 200,
            message: '获取成功',
            data: {
                list: friendList,
                total: result.total,
                totalPage: result.totalPage
            }
        });
    } catch (e) {
        res.json({
            code: 500,
            message: e.message
        });
    }
}

// 获取在线客服列表,promise
const getOnlineServiceList = async () => {
    try {
        const result = await getServiceList({ userType: 3, online: 1 });
        const list = JSON.parse(JSON.stringify(result));
        // 遍历list，从redis中获取好友信息
        const friendList = await Promise.all(list.map(async (item) => {
            const friend = await getChatList({ user: item._id, page: 1, pageSize: 100, isEnd: true });
            return {
                ...item,
                workNum: friend.length
            }
        }));
        return Promise.resolve(friendList);
    } catch (e) {
        console.log('getOnlineServiceList error', e);
        return Promise.reject(e);
    }
}

module.exports = {
    createUserController,
    sysPushMsg,
    initSystemUser,
    createServiceController,
    serviceLoginController,
    serviceListController,
    uploadAvatarController,
    deleteServiceController,
    updateServiceController,
    getUserListController,
    getChatListController,
    getOnlineServiceList
}